package com.findme.unvelouse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

public class FindAddressActivity extends Activity {

	private static final int MENU_ABOUT = Menu.FIRST;

	private static final int DIALOG_ABOUT = 0;

	private static final int MAX_RESULT = 5;

	public static final double LOWER_LEFT_LATITUDE = 43.533118f;

	public static final double LOWER_LEFT_LONGITUDE = 1.360931f;

	public static final double UPPER_RIGHT_LATITUDE = 43.668368f;

	public static final double UPPER_RIGHT_LONGITUDE = 1.511307f;

	private ArrayAdapter<String> adapter;

	private AutoCompleteTextView textView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.findaddress);

		Button goButton = (Button) findViewById(R.id.buttonFind);

		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);
		textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteAddress);
		adapter.setNotifyOnChange(true);
		textView.setAdapter(adapter);

		textView.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// at least 3 character
				if (s.length() >= 3) {
					// adapter.clear();

					AsyncTask<String, Void, ArrayList<String>> task = new AsyncTask<String, Void, ArrayList<String>>() {

						@Override
						protected ArrayList<String> doInBackground(String... params) {

							Geocoder geocoder = new Geocoder(getApplicationContext());

							ArrayList<String> addressList = new ArrayList<String>();

							try {
								List<Address> addresses = geocoder.getFromLocationName(textView.getText().toString(), MAX_RESULT,
										LOWER_LEFT_LATITUDE, LOWER_LEFT_LONGITUDE, UPPER_RIGHT_LATITUDE, UPPER_RIGHT_LONGITUDE);

								for (Address address : addresses) {

									Log.d("FindMeUnVelouse", "Address found = " + address.getAddressLine(0) + ", " + address.getLocality());

									if (address.getLocality() != null) {
										addressList.add(address.getAddressLine(0) + ", " + address.getLocality());
									} else {
										addressList.add(address.getAddressLine(0));
									}

								}

							} catch (IOException e) {
								Log.e("FindMeUnVelouse", "Exception while auto complete : ", e);
							}

							return addressList;
						}

						@Override
						protected void onPostExecute(ArrayList<String> result) {

							Log.d("YourApp", "onPostExecute : " + result.size());
							// update the adapter
							adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_dropdown_item_1line);
							adapter.setNotifyOnChange(true);
							// attach the adapter to textview
							textView.setAdapter(adapter);

							for (String string : result) {

								Log.d("YourApp", "onPostExecute : result = " + string);
								adapter.add(string);
								adapter.notifyDataSetChanged();

							}

							Log.d("YourApp", "onPostExecute : autoCompleteAdapter" + adapter.getCount());

						}

					};

					task.execute(textView.getText().toString());

				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}
		});

		textView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				openGoogleMapActivity();
			}
		});

		// String address = text.getText().get;

		goButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				openGoogleMapActivity();
			}
		});
	}

	protected void openGoogleMapActivity() {

		String address = textView.getText().toString();

		if (address != null) {

			Intent i = new Intent(FindAddressActivity.this, VelouseGoogleMapsActivity.class);
			i.putExtra(VelouseGoogleMapsActivity.KEY_ADDRESS, address);
			FindAddressActivity.this.startActivity(i);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_ABOUT, 0, R.string.About);
		MenuItem item = menu.getItem(0);
		item.setIcon(android.R.drawable.ic_menu_info_details);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ABOUT:
			showDialog(DIALOG_ABOUT);
		}

		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		switch (id) {
		case DIALOG_ABOUT:
			dialog = new Dialog(this);

			dialog.setContentView(R.layout.aboutdialog);
			dialog.setTitle(R.string.About);

			break;
		default:
			dialog = null;
		}
		return dialog;
	}

	// class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
	// @Override
	// // three dots is java for an array of strings
	// protected ArrayList<String> doInBackground(String... args) {
	//
	// Log.d("gottaGo", "doInBackground");
	//
	// ArrayList<String> predictionsArr = new ArrayList<String>();
	//
	// try {
	//
	// URL googlePlaces = new URL(
	// // URLEncoder.encode(url,"UTF-8");
	// "https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
	// + URLEncoder.encode(s.toString(), "UTF-8")
	// + "&types=geocode&language=en&sensor=true&key=<yourapikeygoeshere>");
	// URLConnection tc = googlePlaces.openConnection();
	// BufferedReader in = new BufferedReader(new InputStreamReader(
	// tc.getInputStream()));
	//
	// String line;
	// StringBuffer sb = new StringBuffer();
	// // take Google's legible JSON and turn it into one big string.
	// while ((line = in.readLine()) != null) {
	// sb.append(line);
	// }
	// // turn that string into a JSON object
	// JSONObject predictions = new JSONObject(sb.toString());
	// // now get the JSON array that's inside that object
	// JSONArray ja = new JSONArray(
	// predictions.getString("predictions"));
	//
	// for (int i = 0; i < ja.length(); i++) {
	// JSONObject jo = (JSONObject) ja.get(i);
	// // add each entry to our array
	// predictionsArr.add(jo.getString("description"));
	// }
	// } catch (IOException e) {
	//
	// Log.e("YourApp", "GetPlaces : doInBackground", e);
	//
	// } catch (JSONException e) {
	//
	// Log.e("YourApp", "GetPlaces : doInBackground", e);
	//
	// }
	//
	// return predictionsArr;
	//
	// }
	//
	// // then our post
	//
	// @Override
	// protected void onPostExecute(ArrayList<String> result) {
	//
	// Log.d("YourApp", "onPostExecute : " + result.size());
	// // update the adapter
	// adapter = new ArrayAdapter<String>(getBaseContext(),
	// R.layout.list_item);
	// adapter.setNotifyOnChange(true);
	// // attach the adapter to textview
	// textView.setAdapter(adapter);
	//
	// for (String string : result) {
	//
	// Log.d("YourApp", "onPostExecute : result = " + string);
	// adapter.add(string);
	// adapter.notifyDataSetChanged();
	//
	// }
	//
	// Log.d("YourApp",
	// "onPostExecute : autoCompleteAdapter" + adapter.getCount());
	//
	// }
	//
	// }

}